import { Toast } from 'antd-mobile';
import axios from 'axios';
import React, { useEffect, useState } from 'react';

const AvatarUpload = (props) => {
  const [avatar, setAvatar] = useState(null);
  const [previewUrl, setPreviewUrl] = useState('');
  const [user, setUser] = useState({});

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      setAvatar(file);
      const url = URL.createObjectURL(file);
      setPreviewUrl(url);
    }
  };

  const handleClick = () => {
    document.getElementById('fileInput').click();
  };

  const uploadAvatar = async () => {
    if (!avatar) return;

    const formData = new FormData();
    formData.append('avatar', avatar);
    formData.append('userId', user._id);

    try {
      const response = await axios.post('/cxb/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (response.data.code === 200) {
        Toast.show({
          content: '修改成功',
        });
        sessionStorage.setItem('user', JSON.stringify(response.data.data));
        window.location.reload();
      } else {
        Toast.show({
          content: '修改失败',
        });
      }
    } catch (error) {
      console.error('上传失败:', error);
      Toast.fail('上传失败');
    }
  };

  // 在文件变化后立即上传头像
  useEffect(() => {
    setUser(JSON.parse(sessionStorage.getItem('users')));
    if (avatar) {
      uploadAvatar();
    }
  }, [avatar]);

  return (
    <div>
      <input
        type="file"
        accept="image/*"
        id="fileInput"
        style={{ display: 'none' }}
        onChange={handleFileChange}
      />
      <img
        src={previewUrl || user.avatar} // 默认头像
        alt=""
        onClick={handleClick}
        style={{ width: '100px', height: '100px', cursor: 'pointer', borderRadius: '50%' }}
      />
    </div>
  );
};

export default AvatarUpload;
